package com.electric.electric.serviceimpl;


import com.electric.electric.POJO.Entity.admin.SysPermission;
import com.electric.electric.POJO.Entity.admin.SysRole;
import com.electric.electric.POJO.Entity.admin.SysUser;
import com.electric.electric.mapper.admin.AuthenticationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户验证处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AuthenticationMapper authenticationMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        SysUser user = authenticationMapper.selectUserByUsername(username);
        if (user == null) {
            System.out.println("用户不存在");
            return null;
        }

        // 2. 查询用户角色
        List<SysRole> roles = authenticationMapper.selectRolesByUserId(user.getId());
        if (roles.isEmpty()) {
            throw new UsernameNotFoundException("用户未分配角色");
        }

        // 3. 查询角色对应的权限
        Set<GrantedAuthority> authorities = new HashSet<>();
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode())); // 例如 "ADMIN"
            // 查询当前角色的权限
            List<SysPermission> permissions = authenticationMapper.selectPermissionsByRoleId(role.getId());
            for (SysPermission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getPermCode()));
            }
        }

        return new User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
}
